﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using bpms.Enums;
using bpms.Models;
using bpms.Service;

namespace bpms.Controllers
{
    /// <summary>
    /// 登录注册模块
    /// </summary>
    public class AccountController : Controller
    {
        private readonly AdminUserService _adminUserService;
        private readonly CustomerService _customerService;
        public AccountController(AdminUserService adminUserService, CustomerService customerService)
        {
            _adminUserService = adminUserService;
            _customerService = customerService;
        }
        // GET: 默认登录页
        public IActionResult Login()
        {
            var model = new LoginViewModel();
            return View(model);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid) return View(model);

            ClaimsIdentity identity = null;

            if (model.UserType == UserType.Admin)
            {
                // 查询管理员用户
                var admin = _adminUserService.GetAdminByLoginNameAndPwd(model.LoginName, model.Password);
                if (admin == null)
                {
                    ModelState.AddModelError("", "管理员账号或密码错误");
                    return View(model);
                }
                identity = CreateAdminIdentity(admin);
            }
            else
            {
                //查询顾客
                var customer = _customerService.GetByLoginNameAndPwd(model.LoginName, model.Password);
                if (customer == null)
                {
                    ModelState.AddModelError("", "买家账号或密码错误");
                    return View(model);
                }
                identity = CreateBuyerIdentity(customer);
            }

            var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                principal);

            if (model.UserType == UserType.Admin)
            {
                //管理员登录后默认到顾客列表
                return RedirectToAction("Index", "Customer");
            }
            else
            {
                //买家登录后默认到商品列表
                return RedirectToAction("Index", "Product");
            }
        }

        /// <summary>
        /// 跳转到注册页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Register()
        {
            var model = new RegisterViewModel();
            return View(model);
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            //如果是管理员，不需要填写地址
            if (model.UserType == UserType.Admin)
            {
                ModelState.Remove("Address");
            }
            if (!ModelState.IsValid) return View(model);

            // 检查用户名是否存在
            if (await CheckLoginNameExists(model.UserType, model.LoginName))
            {
                ModelState.AddModelError("LoginName", "登录名已存在");
                return View(model);
            }

            if (model.UserType == UserType.Admin)
            {
                //添加管理员
                var adminUserModel = new AdminUser
                {
                    LoginName = model.LoginName,
                    Name = model.Name,
                    Password = model.Password,
                    Phone=model.Phone
                };
                _adminUserService.Add(adminUserModel);
            }
            else
            {
                //添加顾客
                var customerModel = new Customer
                {
                    LoginName = model.LoginName,
                    Name = model.Name,
                    Password = model.Password,
                    Phone = model.Phone,
                    Address = model.Address
                };
                _customerService.Add(customerModel);
            }
            return RedirectToAction("Login");

        }

        [HttpPost]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            return RedirectToAction("Login", "Account");
        }

        /// <summary>
        /// 检查登录名是否被使用
        /// </summary>
        /// <param name="userType"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        private async Task<bool> CheckLoginNameExists(UserType userType, string loginName)
        {
            if (userType == UserType.Admin)
            {
                var admin = _adminUserService.GetByLoginName(loginName);
                return admin != null;
            }
            else
            {
                var customer = _customerService.GetByLoginName(loginName);
                return customer != null;
            }
        }
        private ClaimsIdentity CreateAdminIdentity(AdminUser admin)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, admin.Id.ToString()),
                new Claim(ClaimTypes.Name, admin.Name),
                new Claim(ClaimTypes.Role, "Admin"),
                new Claim("UserType", ((int)UserType.Admin).ToString())
            };
            return new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        }
        private ClaimsIdentity CreateBuyerIdentity(Customer customer)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, customer.Id.ToString()),
                new Claim(ClaimTypes.Name, customer.Name),
                new Claim(ClaimTypes.Role, "Costomer"),
                new Claim("UserType", ((int)UserType.Customer).ToString())
            };
            return new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        }

    }
}
